#include "key.h"

//矩阵按键扫描
uchar key_scan() {
	uint key_new;  //16位
	uchar key_val = 0; //返回值
	
	P44 = 0; P42 = 1; P35 = 1; P34 = 1; //扫描第一列
	key_new = P3 & 0x0F;
	P44 = 1; P42 = 0; P35 = 1; P34 = 1; //扫描第二列
	key_new = (key_new << 4) | (P3 & 0x0F);
	P44 = 1; P42 = 1; P35 = 0; P34 = 1; //扫描第三列
	key_new = (key_new << 4) | (P3 & 0x0F);
	P44 = 1; P42 = 1; P35 = 1; P34 = 0; //扫描第四列
	key_new = (key_new << 4) | (P3 & 0x0F);
	
	switch(~key_new) { //匹配键码
		case 0x8000: key_val = 4; break;
		case 0x4000: key_val = 5; break;
		case 0x2000: key_val = 6; break;
		case 0x1000: key_val = 7; break;
		
		case 0x0800: key_val = 8; break;
		case 0x0400: key_val = 9; break;
		case 0x0200: key_val = 10; break;
		case 0x0100: key_val = 11; break;
		
		case 0x0080: key_val = 12; break;
		case 0x0040: key_val = 13; break;
		case 0x0020: key_val = 14; break;
		case 0x0010: key_val = 15; break;
		
		case 0x0008: key_val = 16; break;
		case 0x0004: key_val = 17; break;
		case 0x0002: key_val = 18; break;
		case 0x0001: key_val = 19; break;
	}
	return key_val;
}

//独立按键扫描
uchar key_scan_btn() {
	uchar key_val = 0; //返回值
	
	if(P30 == 0) {
		delay(10); while(P33 == 0); delay(10); key_val = 7;
	} else if(P31 == 0)  {
		delay(10); while(P33 == 0); delay(10); key_val = 6;
	} else if(P32 == 0)  {
		delay(10); while(P33 == 0); delay(10); key_val = 5;
	} else if(P33 == 0)  {
		delay(10); while(P33 == 0); delay(10); key_val = 4;
	}
	return key_val;
}
